package com.btex.app;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.entity.BtexInfo;
import com.btex.app.entity.FuturesInfo;
import com.btex.app.entity.TexchangeRateInfo;
import com.btex.app.kine.kline.KData;
import com.btex.app.kine.kline.NewKLineView;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.Tools;
import com.google.gson.Gson;
import com.guoziwei.klinelib.chart.KLineView;
import com.guoziwei.klinelib.model.HisData;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class KLineFullActivity extends BaseActivity {


    @BindView(R.id.activity_kine_k_full)
    KLineView mKLineView;
    @BindView(R.id.activity_full_k_iv_back)
    ImageView mActivityFullKIvBack;
    @BindView(R.id.kine_activity_five_full)
    TextView mKineActivityFiveFull;
    @BindView(R.id.kine_activity_fifteen_full)
    TextView mKineActivityFifteenFull;
    @BindView(R.id.kine_activity_thirty_full)
    TextView mKineActivityThirtyFull;
    @BindView(R.id.kine_activity_one_hours_full)
    TextView mKineActivityOneHoursFull;
    @BindView(R.id.kine_activity_one_day_full)
    TextView mKineActivityOneDayFull;
    @BindView(R.id.activity_full_tv_name)
    TextView mActivityFullTvName;
    @BindView(R.id.activity_full_tv_price)
    TextView mActivityFullTvPrice;
    @BindView(R.id.activity_full_tv_baifenbi)
    TextView mActivityFullTvBaifenbi;
    @BindView(R.id.activity_full_tv_vol)
    TextView mActivityFullTvVol;
    @BindView(R.id.activity_full_tv_heli_type)
    TextView mActivityFullTvHeliType;
    @BindView(R.id.activity_full_tv_heli_value)
    TextView mActivityFullTvHeliValue;
    @BindView(R.id.activity_full_lin_heli)
    LinearLayout mActivityFullLinHeli;
    @BindView(R.id.activity_full_tv_zhishu_type)
    TextView mActivityFullTvZhishuType;
    @BindView(R.id.activity_full_tv_zhishu_value)
    TextView mActivityFullTvZhishuValue;
    @BindView(R.id.activity_full_lin_zhishu)
    LinearLayout mActivityFullLinZhishu;
    @BindView(R.id.kine_activity_one_4_hours)
    TextView mKineActivityOne4Hours;
    @BindView(R.id.kine_activity_one_day)
    TextView mKineActivityOneDay;
    @BindView(R.id.kine_activity_one_week)
    TextView mKineActivityOneWeek;
    @BindView(R.id.activity_full_ma)
    TextView mActivityFullMa;
    @BindView(R.id.activity_full_ema)
    TextView mActivityFullEma;
    @BindView(R.id.activity_full_boll)
    TextView mActivityFullBoll;
    @BindView(R.id.activity_full_macd)
    TextView mActivityFullMacd;
    @BindView(R.id.activity_full_kdj)
    TextView mActivityFullKdj;
    @BindView(R.id.activity_full_rsl)
    TextView mActivityFullRsl;
    private List<HisData> mHisDatas;
    private MicroAVLIDialog mMicroAVLIDialog;
    private String mPair;
    public boolean isShow;
    public boolean isShowKdj;
    private TextView mPop_clssify_types_d;
    public String times = "5";
    public boolean isActivityShow;
    private NewKLineView mFull_new_kine;
    private String mContract_id;
    public int size = 0;
    public double old = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kline_full);
        ButterKnife.bind(this);
        mPair = getIntent().getExtras().getString("pair");
        mContract_id = getIntent().getExtras().getString("contract_id");
        mMicroAVLIDialog = new MicroAVLIDialog(this);
        mMicroAVLIDialog.show();
        mActivityFullMa.setSelected(true);
        mActivityFullMacd.setSelected(true);

        mFull_new_kine = (NewKLineView) findViewById(R.id.full_new_kine);
        mFull_new_kine.setCrossHairMoveMode(2);
        mFull_new_kine.setOnRequestDataListListener(new NewKLineView.OnRequestDataListListener() {
            @Override
            public void requestData() {

            }
        });
        mKineActivityFiveFull.setSelected(true);

        if (!TextUtils.isEmpty(mContract_id)) {

            geTexchangeRate();
        }

        if (!TextUtils.isEmpty(mPair)) {

            mActivityFullLinHeli.setVisibility(View.INVISIBLE);
            mActivityFullLinZhishu.setVisibility(View.INVISIBLE);
            geTexchange();
        }
        if (mMicroAVLIDialog != null) {
            mMicroAVLIDialog.show();
        }
        initInfo("15m");
        initOnclik();

    }

    private int dp2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    private void initOnclik() {


    }

    @Override
    public void setData() {

    }

    @Override
    public void onClick(View view) {

    }

    private void initInfo(String time) {


        String urls = "";

//        RequestParams params = new RequestParams();
//
//        params.addQueryStringParameter("limit", "600");
//        params.addQueryStringParameter("type", time);


        HashMap<String, String> stringStringHashMap = new HashMap<>();

        if (mContract_id != null) {
//            params.addQueryStringParameter("symbol", mContract_id);
            stringStringHashMap.put("symbol", mContract_id);
            urls = Config.K_DATA;
        } else {
//            params.addQueryStringParameter("symbol", mPair);
            stringStringHashMap.put("symbol", mPair);
            urls = Config.URL_APP_BTEX;
        }

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        OkGo.<String>get(urls + "?rnd=" + String.valueOf(num)).params(stringStringHashMap).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.dismiss();
                }

                String result = response.body();

                try {
                    JSONObject jsonObject = new JSONObject(response.body());

                    if (jsonObject.getString("code").equals("1")) {
                        setKineData(result);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });
//
//        HttpHandler<String> send = new HttpUtils().send(HttpRequest.HttpMethod.GET, urls + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                if (mMicroAVLIDialog != null) {
//                    mMicroAVLIDialog.dismiss();
//                }
//
//
//                String result = responseInfo.result;
//
//                try {
//                    JSONObject jsonObject = new JSONObject(responseInfo.result);
//
//                    if (jsonObject.getString("code").equals("1")) {
//                        setKineData(result);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//                Toast.makeText(cxt, msg, Toast.LENGTH_SHORT).show();
//
//            }
//        });
    }


    private Handler handler = new Handler() {

    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (isActivityShow) {

                if (times.equals("15")) {

                    initInfo("15m");
                } else if (times.equals("5")) {
                    initInfo("5m");
                } else if (times.equals("30")) {
                    initInfo("30m");
                } else if (times.equals("1h")) {
                    initInfo("1h");
                } else if (times.equals("1d")) {
                    initInfo("1d");
                } else if (times.equals("1w")) {
                    initInfo("1w");
                } else if (times.equals("4h")) {
                    initInfo("4h");
                } else if (times.equals("1")) {
                    Log.i("kejkwejkwhuef", "1");
                    initInfo("1m");
                }

                handler.postDelayed(this, 5000);
            } else {
                return;
            }


        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        isActivityShow = true;
        handler.postDelayed(runnable, 5000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivityShow = false;
    }


    private void setKineData(String result) {
        Gson gson = new Gson();
        BtexInfo btexInfo = gson.fromJson(result, BtexInfo.class);
        List<List<String>> lists = btexInfo.getData().getLists();

        List<KData> dataList = new ArrayList<>();

        double openPrice;
        double closePrice;
        double maxPrice;
        double minPrice;
        double volume;
        long kinetime;


        if (lists.size() > 0) {

            for (int i = 0; i < lists.size(); i++) {

//            时间
                kinetime = Long.valueOf(lists.get(i).get(0));
//            开盘价
                openPrice = Double.valueOf(lists.get(i).get(1));
//            最高价
                maxPrice = Double.valueOf(lists.get(i).get(2));
//            最低价
                minPrice = Double.valueOf(lists.get(i).get(3));
//            收盘价
                closePrice = Double.valueOf(lists.get(i).get(4));
//            成交量
                volume = Double.valueOf(lists.get(i).get(5));
//            填充数据
                dataList.add(new KData(kinetime, openPrice, closePrice, maxPrice, minPrice, volume));
//            最后的成交价就是开盘价
                openPrice = closePrice;

            }


            if (size > 0) {
                mFull_new_kine.resetDataList(dataList);
            } else {
                mFull_new_kine.initKDataList(dataList);
            }


            mFull_new_kine.setDeputyPicShow(true);

            size++;


        }


    }


    @OnClick({R.id.activity_full_ma, R.id.activity_full_ema, R.id.activity_full_boll, R.id.activity_full_macd, R.id.activity_full_kdj, R.id.activity_full_rsl, R.id.activity_full_k_iv_back, R.id.kine_activity_five_full, R.id.kine_activity_fifteen_full, R.id.kine_activity_thirty_full, R.id.kine_activity_one_hours_full, R.id.kine_activity_one_day_full, R.id.kine_activity_one_4_hours, R.id.kine_activity_one_day, R.id.kine_activity_one_week})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_full_ma:
                setMAListState();
                mActivityFullMa.setSelected(true);
                mFull_new_kine.setMainImgType(NewKLineView.MAIN_IMG_MA);

                break;
            case R.id.activity_full_ema:
                setMAListState();
                mActivityFullEma.setSelected(true);
                mFull_new_kine.setMainImgType(NewKLineView.MAIN_IMG_EMA);

                break;
            case R.id.activity_full_boll:
                setMAListState();
                mActivityFullBoll.setSelected(true);
                mFull_new_kine.setMainImgType(NewKLineView.MAIN_IMG_BOLL);

                break;
            case R.id.activity_full_macd:
                setMACDState();
                mActivityFullMacd.setSelected(true);
                mFull_new_kine.setDeputyImgType(NewKLineView.DEPUTY_IMG_MACD);

                break;
            case R.id.activity_full_kdj:
                setMACDState();
                mActivityFullKdj.setSelected(true);
                mFull_new_kine.setDeputyImgType(NewKLineView.DEPUTY_IMG_KDJ);

                break;
            case R.id.activity_full_rsl:
                setMACDState();
                mActivityFullRsl.setSelected(true);
                mFull_new_kine.setDeputyImgType(NewKLineView.DEPUTY_IMG_RSI);

                break;

            case R.id.activity_full_k_iv_back:

                finish();
                break;

            case R.id.kine_activity_five_full:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "1";
                size = 0;
                SetStat();
                mKineActivityFiveFull.setSelected(true);
                initInfo("1m");

                break;
            case R.id.kine_activity_fifteen_full:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "5";
                size = 0;
                SetStat();
                mKineActivityFifteenFull.setSelected(true);
                initInfo("5m");
                break;
            case R.id.kine_activity_thirty_full:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "15";
                size = 0;
                SetStat();
                mKineActivityThirtyFull.setSelected(true);
                initInfo("15m");
                break;
            case R.id.kine_activity_one_hours_full:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "30";
                size = 0;
                SetStat();
                mKineActivityOneHoursFull.setSelected(true);
                initInfo("30m");

                break;
            case R.id.kine_activity_one_day_full:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "1h";
                size = 0;
                SetStat();
                mKineActivityOneDayFull.setSelected(true);
                initInfo("1h");

                break;

            case R.id.kine_activity_one_4_hours:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "4h";
                SetStat();
                mKineActivityOne4Hours.setSelected(true);
                initInfo("4h");

                break;

            case R.id.kine_activity_one_day:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "1d";
                SetStat();
                mKineActivityOneDay.setSelected(true);
                initInfo("1d");
                break;

            case R.id.kine_activity_one_week:
                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.show();
                }
                times = "1w";
                SetStat();
                mKineActivityOneWeek.setSelected(true);
                initInfo("1w");

                break;
        }
    }


    public void SetStat() {
        mKineActivityFiveFull.setSelected(false);
        mKineActivityFifteenFull.setSelected(false);
        mKineActivityThirtyFull.setSelected(false);
        mKineActivityOneHoursFull.setSelected(false);
        mKineActivityOneDayFull.setSelected(false);
        mKineActivityOne4Hours.setSelected(false);
        mKineActivityOneDay.setSelected(false);
        mKineActivityOneWeek.setSelected(false);

    }


    public void geTexchangeRate() {

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("contract_id", mContract_id);
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num)).params("contract_id", mContract_id).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {


                        setTexchangeRate(response.body());


                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });
//        new HttpUtils().send(HttpRequest.HttpMethod.GET, Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                String result = responseInfo.result;
//                Log.i("sjeuwyeuwye", responseInfo.result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//
//
//                        setTexchangeRate(responseInfo.result);
//
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//        });
    }

    private void setTexchangeRate(String result) {

//        mTreatyTvNewIndex.setText("最新指数:" + "\t" + Tools.round(Double.valueOf(mFuturesInfo.getData().getTicker().getIndex_price()), Integer.valueOf(mPrice_float_num)).toString());
//        mTreatyTvHeliPrice.setText("合理价格:" + "\t" + Tools.round(Double.valueOf(mFuturesInfo.getData().getTicker().getMark_price()), Integer.valueOf(mPrice_float_num)).toString());

        Gson gson = new Gson();
        FuturesInfo futuresInfo = gson.fromJson(result, FuturesInfo.class);
        String pair = futuresInfo.getData().getPair();
        String amount = futuresInfo.getData().getTicker().getAmount();
        double mark_price = futuresInfo.getData().getTicker().getMark_price();
        double index_price = futuresInfo.getData().getTicker().getIndex_price();
        double trade_price = futuresInfo.getData().getTicker().getTrade_price();
        double change_24h = futuresInfo.getData().getTicker().getChange_24h();
        String change_24htrim = Tools.round(change_24h, 4).toString().trim();
        String trade_pricetrim = Tools.round(trade_price, 4).toString().trim();
        String mark_pricetrim = Tools.round(mark_price, 4).toString().trim();
        String index_pricetrim = Tools.round(index_price, 4).toString().trim();


        if (old > mark_price) {
            mActivityFullTvPrice.setTextColor(getResources().getColor(R.color.red));
            mActivityFullTvBaifenbi.setTextColor(getResources().getColor(R.color.red));

        } else if (old == mark_price) {

        } else {
            mActivityFullTvPrice.setTextColor(getResources().getColor(R.color.green));
            mActivityFullTvBaifenbi.setTextColor(getResources().getColor(R.color.green));
        }

        old = mark_price;

        String trim = Tools.round(Double.valueOf(change_24htrim) * 100, 2).toString().trim();
        mActivityFullTvBaifenbi.setText(trim + "%");
        mActivityFullTvVol.setText(amount);
        mActivityFullTvPrice.setText(trade_pricetrim);
        mActivityFullTvHeliValue.setText(mark_pricetrim);
        mActivityFullTvZhishuValue.setText(index_pricetrim);
        mActivityFullTvName.setText(pair);


    }


    public void geTexchange() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter(Config.KEY_PAIR, mPair);
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.URL_PAIR + "?rnd=" + String.valueOf(num)).params(Config.KEY_PAIR, mPair).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();
//                Log.i("kwjehfuwihefweui", responseInfo.result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {

                        Gson gson = new Gson();
                        TexchangeRateInfo texchangeRateInfo = gson.fromJson(result, TexchangeRateInfo.class);
                        String change_24h = texchangeRateInfo.getData().getChange_24h();
                        Double aDouble = Double.valueOf(change_24h);
                        if (aDouble < 0) {
                            mActivityFullTvBaifenbi.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            mActivityFullTvBaifenbi.setTextColor(getResources().getColor(R.color.green));
                        }
                        mActivityFullTvName.setText(texchangeRateInfo.getData().getPair());


                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });


//        new HttpUtils().send(HttpRequest.HttpMethod.GET, Config.URL_PAIR + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                String result = responseInfo.result;
////                Log.i("kwjehfuwihefweui", responseInfo.result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//
//                        Gson gson = new Gson();
//                        TexchangeRateInfo texchangeRateInfo = gson.fromJson(result, TexchangeRateInfo.class);
//                        String change_24h = texchangeRateInfo.getData().getChange_24h();
//                        Double aDouble = Double.valueOf(change_24h);
//                        if (aDouble < 0) {
//                            mActivityFullTvBaifenbi.setTextColor(getResources().getColor(R.color.red));
//                        } else {
//                            mActivityFullTvBaifenbi.setTextColor(getResources().getColor(R.color.green));
//                        }
//                        mActivityFullTvName.setText(texchangeRateInfo.getData().getPair());
//
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//        });
    }


    public void setMAListState() {
        mActivityFullMa.setSelected(false);
        mActivityFullEma.setSelected(false);
        mActivityFullBoll.setSelected(false);
    }

    public void setMACDState() {
        mActivityFullMacd.setSelected(false);
        mActivityFullKdj.setSelected(false);
        mActivityFullRsl.setSelected(false);

    }


}
